package com.casems.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import com.casems.commons.execption.ParamExecption;
import com.casems.commons.vo.ResultVO;
import com.casems.service.SMSService;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping
@Slf4j
public class CodeController {

    @Autowired
    DefaultKaptcha kaptcha;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    SMSService smsService;

    public static final String CODE_PREFIX ="code:";

    @GetMapping("/code")
    public ResultVO getCode(){
        String text = kaptcha.createText();

        BufferedImage image = kaptcha.createImage(text);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image,"jpeg",outputStream);
        } catch (IOException e) {
            log.error(e.getMessage(),e);
            return ResultVO.failed("验证码创建失败");
        }
        String uuid = IdUtil.simpleUUID();
        String redisKey = CODE_PREFIX + uuid;

        stringRedisTemplate.opsForValue().set(redisKey,text,1, TimeUnit.MINUTES);

        String codeUrl = "data:image/jpeg;base64," + Base64.encode(outputStream.toByteArray());

        Map<Object, Object> dataMap = MapUtil.builder().put("uuid", uuid).put("codeUrl", codeUrl).build();

        System.out.println("key:" + uuid);
        System.out.println("code:" + text);

        return ResultVO.success(dataMap);
    }

    @GetMapping("/checkCode")
    public ResultVO checkCode(String uuid,String code,String phone) throws Exception {
        String savedCode = stringRedisTemplate.opsForValue()
                .get(CodeController.CODE_PREFIX + uuid);

        // 校验验证码
        if(StringUtils.isEmpty(savedCode)){
            throw new ParamExecption("验证码过期");
        }
        if(!StringUtils.equalsIgnoreCase(savedCode,code)){
            throw  new ParamExecption("验证码错误");
        }
        return smsService.sendCode(phone)?
                ResultVO.success("验证码发送成功"):ResultVO.failed("验证码发送失败");
    }
}
